package com.mes.eventhandler;

import java.util.ArrayList;
import java.util.List;

import javax.enterprise.event.Observes;

import org.apache.log4j.Logger;
import org.openbravo.base.exception.OBException;
import org.openbravo.base.model.Entity;
import org.openbravo.base.model.ModelProvider;
import org.openbravo.client.kernel.event.EntityNewEvent;
import org.openbravo.client.kernel.event.EntityPersistenceEventObserver;
import org.openbravo.client.kernel.event.EntityUpdateEvent;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.ConnectionProvider;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.service.db.DalConnectionProvider;

import com.mes.quality.data.EmesqInspectionGroup;

public class EmesqInspectionGroupEventHandler extends EntityPersistenceEventObserver {

	private static Entity[] entities = { ModelProvider.getInstance().getEntity(EmesqInspectionGroup.ENTITY_NAME) };

	protected Logger logger = Logger.getLogger(this.getClass());

	@Override
	protected Entity[] getObservedEntities() {
		return entities;
	}
	
	private void throwMessage(String message){
		String language = OBContext.getOBContext().getLanguage().getLanguage();
		ConnectionProvider conn = new DalConnectionProvider(false);
		throw new OBException(Utility.messageBD(conn, message, language));
	}
	
	public void onSave(@Observes EntityNewEvent event) {
	    if (!isValidEvent(event)) {
	      return;
	    }
	    final EmesqInspectionGroup emesqInspectionGroup = (EmesqInspectionGroup) event.getTargetInstance();
		String code = emesqInspectionGroup.getCode();
		
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(code);
		//查询该code在哪些机构中存在]
		
		List<EmesqInspectionGroup> list = OBDal.getInstance().createQuery(EmesqInspectionGroup.class, "code=?", paramList).list();
		for (EmesqInspectionGroup tmp : list) {
			//两个机构相等说明存在重复
			if(emesqInspectionGroup.getOrganization().getId().equals(tmp.getOrganization().getId())){
				throwMessage("同一个组织结构内部不允许重复编码");
			}
		}
	}

	public void onUpdate(@Observes EntityUpdateEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
		final EmesqInspectionGroup emesqInspectionGroup = (EmesqInspectionGroup) event.getTargetInstance();
		String code = emesqInspectionGroup.getCode();
		
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(code);
		paramList.add(emesqInspectionGroup.getId());
		//查询该code在哪些机构中存在
		List<EmesqInspectionGroup> list = OBDal.getInstance().createQuery(EmesqInspectionGroup.class, "code=? and id<>?", paramList).list();
		for (EmesqInspectionGroup tmp : list) {
			//两个机构相等说明存在重复
			if(emesqInspectionGroup.getOrganization().getId().equals(tmp.getOrganization().getId())){
				throwMessage("同一个组织结构内部不允许重复编码");
			}
		}
	}

}
